package com.sita.cfmoto.interact.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.sita.cfmoto.R;
import com.sita.cfmoto.event.ReleaseDynamicEvent;
import com.sita.cfmoto.interact.activity.DynamicDetailActivity;
import com.sita.cfmoto.interact.activity.DynamicListActivity;
import com.sita.cfmoto.interact.adapter.PersonPopularRecyclerAdapter;
import com.sita.cfmoto.rest.model.Dynamic;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.BeanUtils;
import com.sita.cfmoto.utils.InteractUtils;
import com.sita.cfmoto.utils.PersistUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class DynamicFragment extends Fragment {
    @Bind(R.id.personal_popular_recycler)
    RecyclerView personPopularRecycler;
    @Bind(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @Bind(R.id.official_more_txt)
    TextView officialMore;
    @Bind(R.id.dynamic_fragment_refresh)
    SwipeRefreshLayout refreshDynamic;
    //    private ImageView[] tips;
//    private List<ImageView> mImageViews;
//    private List<Integer> officialSelectImg;
    private PersonPopularRecyclerAdapter personRecyclerAdapter;
    private GridLayoutManager mGridLayoutManager;
    //    private OfficialSelectViewPagerAdapter officialSelectViewPagerAdapter;
    private List<Dynamic> officialDynamicList = new ArrayList<>();
    private int size = 6;
    private int page = 0;
    private long endDate;
    private boolean isRefresh = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic, null);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initOfficialDynamicList();
        initPersonDynamicList();
        fetchPersonDynamicList();
        fetchOfficialDynamicList();
        refreshDynamic.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isRefresh) {
                    isRefresh = true;
                    fetchPersonDynamicList();
                    fetchOfficialDynamicList();
                }
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(ReleaseDynamicEvent event) {
        if (event.type == Constants.DYNAMIC_SOURCE_PERSONAL) {
            fetchPersonDynamicList();
        }
    }

    private void initOfficialDynamicList() {
        convenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, officialDynamicList)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.round_gray, R.drawable.round_white})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        if (officialDynamicList.get(position) != null) {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), DynamicDetailActivity.class);
                            intent.putExtra("dynamic", officialDynamicList.get(position));
                            startActivity(intent);
                        }

                    }
                });


    }


    @OnClick(R.id.official_more_txt)
    void onClickOfficialMore() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), DynamicListActivity.class);
        intent.putExtra("source", 1);
        startActivity(intent);
    }

    @OnClick(R.id.personal_more_txt)
    void onClickPersonalMore() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), DynamicListActivity.class);
        intent.putExtra("source", 0);
        startActivity(intent);
    }

    private void initPersonDynamicList() {
        mGridLayoutManager = new GridLayoutManager(getActivity(), 3);
        personPopularRecycler.setLayoutManager(mGridLayoutManager);
        personRecyclerAdapter = new PersonPopularRecyclerAdapter();
        personPopularRecycler.setAdapter(personRecyclerAdapter);
        personRecyclerAdapter.setOnItemClickListener(new PersonPopularRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Dynamic dynamic) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), DynamicDetailActivity.class);
                intent.putExtra("dynamic", dynamic);
                startActivity(intent);
            }
        });
    }

    private void fetchPersonDynamicList() {
        endDate = System.currentTimeMillis();
        InteractUtils.fetchDynamicList(2, size, page, null, null, endDate, null, null,
                Constants.DYNAMIC_SOURCE_PERSONAL, 2, new InteractUtils.FetchDynamicListCallback() {
                    @Override
                    public void onDynamicListFetched(List<Dynamic> dynamicList) {
                        refreshDynamic.setRefreshing(false);
                        isRefresh = false;
                        if (dynamicList == null) {
                            dynamicList = new ArrayList<>();
                        }
                        if (dynamicList.isEmpty()) {
                            List<com.sita.cfmoto.persistence.Dynamic> allDynamic = PersistUtils.getDynamic(6, 0);
                            Iterator<com.sita.cfmoto.persistence.Dynamic> iterator = allDynamic.iterator();
                            while (iterator.hasNext()) {
                                com.sita.cfmoto.persistence.Dynamic dynamic = iterator.next();
                                dynamicList.add(BeanUtils.copyProperties(dynamic));
                            }
                        }
                        if (dynamicList.size() == 0) {
                            return;
                        }
                        personRecyclerAdapter.setData(dynamicList);
                    }
                });
    }

    private void fetchOfficialDynamicList() {
        endDate = System.currentTimeMillis();
        InteractUtils.fetchDynamicList(2, 4, 0, null, null, endDate, null, null,
                Constants.DYNAMIC_SOURCE_OFFICIAL, 2, new InteractUtils.FetchDynamicListCallback() {
                    @Override
                    public void onDynamicListFetched(List<Dynamic> dynamicList) {
                        refreshDynamic.setRefreshing(false);
                        if (dynamicList == null) {
                            dynamicList = new ArrayList<>();
                        }
                        if (dynamicList.isEmpty()) {
                            List<com.sita.cfmoto.persistence.Dynamic> allDynamic = PersistUtils.getDynamic(4, 1);
                            Iterator<com.sita.cfmoto.persistence.Dynamic> iterator = allDynamic.iterator();
                            while (iterator.hasNext()) {
                                com.sita.cfmoto.persistence.Dynamic dynamic = iterator.next();
                                dynamicList.add(BeanUtils.copyProperties(dynamic));
                            }
                        }
                        if (dynamicList.size() == 0) {
                            return;
                        }
                        officialDynamicList.clear();
                        officialDynamicList.addAll(dynamicList);
                        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
                        convenientBanner.setPages(
                                new CBViewHolderCreator<LocalImageHolderView>() {
                                    @Override
                                    public LocalImageHolderView createHolder() {
                                        return new LocalImageHolderView();
                                    }
                                }, officialDynamicList);
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        convenientBanner.startTurning(3000);
    }

    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }

    public class LocalImageHolderView implements Holder<Dynamic> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, Dynamic dynamic) {
            Picasso.with(GlobalContext.getGlobalContext()).load(dynamic.picList == null || dynamic.picList.size() == 0 ? null : dynamic.picList.get(0)).placeholder(R.drawable.official_dynamic_default_icon)
                    .into(imageView);
        }
    }

}
